import {queryProductDetail, Addshopping} from "../../api/apis";
import Currency from "currency.js";

let that;
let id;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        detail: null,
        catTotalCount: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        id = options.id;
        that = this
        that.getDetail();
        that.getCatTotalCount()

    },

//获取产品信息详情页
    getDetail() {
        queryProductDetail({id}).then(res => {
            this.setData({
                detail: res.data
            })
            wx.setNavigationBarTitle({
                title: this.data.detail.title,
            })
        })
    },
    /**
     * 购物车
     */
    onClickShopping() {
        wx.switchTab({url: '/pages/shopping/shopping'})
    },
    /**
     * 加入购物车
     */
    onClickAddShopping() {
        let one = Object.assign({}, that.data.detail)
        let proArr = one['price'].split("/")
        let price = parseFloat(proArr[0])
        one['unit'] = proArr[1]
        one['count'] = 1
        one['price'] = Currency(price).value
        let carList = wx.getStorageSync("carList") || []
        let isExist = false
        carList.forEach(item => {
            if (item["_id"] === one["_id"]) {
                item["count"] += one['count']
                item["totalPrice"] = Currency(one['price']).multiply(item["count"]).value
                isExist = true
            }
        })
        if (!isExist) {
            one['check'] = false
            one['totalPrice'] = one['price']
            carList.push(one)
        }
        wx.setStorageSync("carList", carList)
        wx.showToast({
            title: '添加成功',
            icon: 'none'
        })
        that.getCatTotalCount()

    },
    /**
     * 购物车总数量
     */
    getCatTotalCount() {
        let carList = wx.getStorageSync("carList") || []
        let catTotalCount = 0;
        carList.forEach(item => {
            catTotalCount += item["count"]
        })
        that.setData({catTotalCount})
    },

    /**
     * 立刻购买
     */
    onClickBuy() {
        wx.showToast({
            title: '购买成功',
            icon: 'none'
        })
    }

})

